<template>
  <div>
    <!-- 引用 AccountComponent -->
    <AccountComponent
      :account-data="accountData"
      :user-data="userData"
      @add-user="handleAddUser"
      @edit-user="handleEditUser"
      @delete-user="handleDeleteUser"
      @apply-for-account="handleApplyForAccount"
      @edit-account="handleEditAccount"
    />

    <el-dialog
      title="添加用户"
      :visible.sync="dialogFormVisibleAddUser"
      width="600px"
    >
      <el-form :model="addUserForm">
        <el-form-item
          label="昵称"
          :label-width="formLabelWidth"
          style="margin-right: 160px"
        >
          <el-input
            v-model="addUserForm.userUsername"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="联系平台"
          :label-width="formLabelWidth"
          style="margin-right: 160px"
        >
          <el-input
            v-model="addUserForm.userContactWay"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="充值日期"
          :label-width="formLabelWidth"
          style="margin-right: 160px"
        >
          <el-date-picker
            v-model="addUserForm.userPaymentDate"
            align="right"
            type="date"
            placeholder="选择日期"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="有效期至"
          :label-width="formLabelWidth"
          style="margin-right: 160px"
        >
          <el-date-picker
            v-model="addUserForm.userPaymentNextdate"
            align="right"
            type="date"
            placeholder="选择日期"
            :picker-options="pickerOptionsFuture"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="充值金额"
          :label-width="formLabelWidth"
          style="margin-right: 160px"
        >
          <el-input
            v-model="addUserForm.userPaymentAmount"
            autocomplete="off"
            type="number"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="服务名"
          :label-width="formLabelWidth"
          style="margin-right: 160px"
        >
          <el-input
            v-model="addUserForm.userServiceName"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="备注"
          :label-width="formLabelWidth"
          style="margin-right: 160px"
        >
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
            v-model="addUserForm.userDetail"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleAddUser = false">取 消</el-button>
        <el-button type="primary" @click="addUserSubmit()">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="修改用户信息"
      :visible.sync="dialogFormVisibleEditUser"
      width="600px"
    >
      <el-form :model="editUserForm">
        <el-form-item
          label="昵称"
          :label-width="formLabelWidth"
          style="margin-right: 160px"
        >
          <el-input
            v-model="editUserForm.userUsername"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="联系平台"
          :label-width="formLabelWidth"
          style="margin-right: 160px"
        >
          <el-input
            v-model="editUserForm.userContactWay"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="充值日期"
          :label-width="formLabelWidth"
          style="margin-right: 160px"
        >
          <el-date-picker
            v-model="editUserForm.userPaymentDate"
            align="right"
            type="date"
            placeholder="选择日期"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="有效期至"
          :label-width="formLabelWidth"
          style="margin-right: 160px"
        >
          <el-date-picker
            v-model="editUserForm.userPaymentNextdate"
            align="right"
            type="date"
            placeholder="选择日期"
            :picker-options="pickerOptionsFuture"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="充值金额"
          :label-width="formLabelWidth"
          style="margin-right: 160px"
        >
          <el-input
            v-model="editUserForm.userPaymentAmount"
            autocomplete="off"
            type="number"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="服务名"
          :label-width="formLabelWidth"
          style="margin-right: 160px"
        >
          <el-input
            v-model="editUserForm.userServiceName"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="备注"
          :label-width="formLabelWidth"
          style="margin-right: 160px"
        >
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
            v-model="editUserForm.userDetail"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleEditUser = false">取 消</el-button>
        <el-button type="primary" @click="editUserSubmit()">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="修改账户信息"
      :visible.sync="dialogFormVisibleEditAccount"
      width="800px"
    >
      <el-form :model="editAccountForm">
        <el-form-item
          label="GPT&Gmail账号"
          :label-width="formLabelWidth"
          style="margin-right: 120px"
        >
          <el-input
            v-model="editAccountForm.accountGmail"
            :disabled="true"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="GPT密码"
          :label-width="formLabelWidth"
          style="margin-right: 120px"
        >
          <el-input
            v-model="editAccountForm.accountChatgptPassword"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="Gmail密码"
          :label-width="formLabelWidth"
          style="margin-right: 120px"
        >
          <el-input
            v-model="editAccountForm.accountGmailPassword"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="备注"
          :label-width="formLabelWidth"
          style="margin-right: 120px"
        >
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
            v-model="editAccountForm.accountDetails"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          label="银行卡尾号"
          :label-width="formLabelWidth"
          style="margin-right: 120px"
        >
          <el-input
            v-model="editAccountForm.accountBankNumber"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleEditUser = false">取 消</el-button>
        <el-button type="primary" @click="editAccountSubmit()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分页组件 -->
    <div class="block">
      <el-pagination
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>
  
  <script>
import AccountComponent from "@/components/AccountComponent";
import axios from "axios";
import { mapGetters } from "vuex";

export default {
  name: "AccountView",
  components: {
    AccountComponent,
  },
  data() {
    return {
      accountData: {}, // 账户信息
      userData: [], // 用户列表
      total: 1, // 数据总数
      currentPage: 1, // 当前页码
      pageSize: 1,
      accountId: 0,
      dialogFormVisibleAddUser: false,
      dialogFormVisibleEditUser: false,
      dialogFormVisibleEditAccount: false,
      addUserForm: {
        userUsername: "",
        userContactWay: "",
        userPaymentDate: "",
        userPaymentNextdate: "",
        userPaymentAmount: 0,
        userDetail: "",
        userServiceName:""
      },
      editUserForm: {
        userUsername: "",
        userContactWay: "",
        userPaymentDate: "",
        userPaymentNextdate: "",
        userPaymentAmount: 0,
        userDetail: "",
        userServiceName:""
      },
      editAccountForm: {
        accountGmail: "",
        accountGmailPassword: "",
        accountChatgptPassword: "",
        accountDetails: "",
        accountBankNumber: "",
      },
      formLabelWidth: "180px",
      editUserId: 0,
      accountOperatorId: 0,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "前天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 2);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      pickerOptionsFuture: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
        shortcuts: [
          {
            text: "30天后",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 30);
              picker.$emit("pick", date);
            },
          },
          {
            text: "60天后",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 60);
              picker.$emit("pick", date);
            },
          },
          {
            text: "90天后",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 90);
              picker.$emit("pick", date);
            },
          },
          {
            text: "180天后",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 180);
              picker.$emit("pick", date);
            },
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters("user", ["user"]), // 从 user 模块中获取 user
  },
  methods: {
    // 获取用户数据
    async fetchAccountData() {
      try {
        const response = await axios.get(
          "http://8.155.162.119/api/account/getAccount",
          {
            params: {
              operatorId: this.user.id,
              pageNum: this.currentPage,
            },
          }
        );
        this.parseAccountData(response.data.data.data);
        this.$message.success("获取账户信息成功");
      } catch (error) {
        console.error("获取账户数据失败：", error);
        this.$message.error("无法获取账户数据");
      }
    },
    parseAccountData(data) {
      this.total = data.total;
      this.accountData = data.account;
      this.userData = data.users;
      this.accountId = data.account.accountId;
      this.accountOperatorId = data.account.accountOperatorId;
    },

    handlePageChange(page) {
      console.log("当前页码:", page);
      this.currentPage = page;
      this.fetchAccountData(); // 切换页码时重新获取账户数据
    },

    // 处理添加用户
    handleAddUser() {
      this.dialogFormVisibleAddUser = true;
    },
    async addUserSubmit() {
      try {
        await axios.get("http://8.155.162.119/api/user/addUser", {
          params: {
            userUsername: this.addUserForm.userUsername,
            userContactWay: this.addUserForm.userContactWay,
            userPaymentDate: this.addUserForm.userPaymentDate,
            userPaymentNextdate: this.addUserForm.userPaymentNextdate,
            userPaymentAmount: this.addUserForm.userPaymentAmount,
            userDetail: this.addUserForm.userDetail,
            userAccountKey: this.accountId,
            userServiceName:this.addUserForm.userServiceName
          },
        });
        this.addUserForm.userUsername = "";
        this.addUserForm.userContactWay = "";
        this.addUserForm.userPaymentDate = "";
        this.addUserForm.userPaymentNextdate = "";
        this.addUserForm.userPaymentAmount = 0;
        this.addUserForm.userDetail = "";
        this.addUserForm.userServiceName = "";
        this.$message.success("添加用户成功");
      } catch (error) {
        console.error("添加用户失败：", error);
        this.$message.error("无法添加用户");
      }
      this.dialogFormVisibleAddUser = false;
      this.fetchAccountData(); // 重新获取账户数据
    },

    // 处理编辑用户
    handleEditUser(userId) {
      this.$message.info(`正在编辑用户：${userId}`);
      this.editUserId = userId;
      // 通过Id获取用户的信息
      this.getUserByUserId();
      this.dialogFormVisibleEditUser = true;
    },
    async editUserSubmit() {
      try {
        await axios.get("http://8.155.162.119/api/user/updateUser", {
          params: {
            userId: this.editUserId,
            userUsername: this.editUserForm.userUsername,
            userContactWay: this.editUserForm.userContactWay,
            userPaymentDate: this.editUserForm.userPaymentDate,
            userPaymentNextdate: this.editUserForm.userPaymentNextdate,
            userPaymentAmount: this.editUserForm.userPaymentAmount,
            userDetail: this.editUserForm.userDetail,
            userAccountKey: this.accountId,
            userServiceName:this.editUserForm.userServiceName
          },
        });
        this.editUserForm.userUsername = "";
        this.editUserForm.userContactWay = "";
        this.editUserForm.userPaymentDate = "";
        this.editUserForm.userPaymentNextdate = "";
        this.editUserForm.userPaymentAmount = 0;
        this.editUserForm.userDetail = "";
        this.$message.success("修改用户信息成功");
      } catch (error) {
        console.error("修改用户信息失败：", error);
        this.$message.error("无法修改用户信息");
      }
      this.dialogFormVisibleEditUser = false;
      this.fetchAccountData(); // 重新获取账户数据
    },
    async getUserByUserId() {
      try {
        const response = await axios.get(
          "http://8.155.162.119/api/user/getUserByUserId",
          {
            params: {
              userId: this.editUserId,
            },
          }
        );
        this.editUserForm.userUsername = response.data.data.userUsername;
        this.editUserForm.userContactWay = response.data.data.userContactWay;
        this.editUserForm.userPaymentDate = response.data.data.userPaymentDate;
        this.editUserForm.userPaymentNextdate =
          response.data.data.userPaymentNextdate;
        this.editUserForm.userPaymentAmount =
          response.data.data.userPaymentAmount;
        this.editUserForm.userDetail = response.data.data.userDetail;
      } catch (error) {
        console.error("获取单个用户信息失败：", error);
        this.$message.error("无法获取单个用户信息");
      }
    },

    // 处理修改账号
    async handleEditAccount() {
      this.$message.info(`正在编辑账户：${this.accountId}`);
      // 通过Id获取账号的信息
      this.getAccountByAccoundId();
      this.dialogFormVisibleEditAccount = true;
    },
    async getAccountByAccoundId() {
      this.editAccountForm.accountGmail = this.accountData.accountGmail;
      this.editAccountForm.accountGmailPassword =
        this.accountData.accountGmailPassword;
      this.editAccountForm.accountChatgptPassword =
        this.accountData.accountChatgptPassword;
      this.editAccountForm.accountDetails = this.accountData.accountDetails;
      this.editAccountForm.accountBankNumber =
        this.accountData.accountBankNumber;
    },
    async editAccountSubmit() {
      try {
        await axios.get("http://8.155.162.119/api/account/updateAccount", {
          params: {
            accountId: this.accountId,
            accountGmail: this.editAccountForm.accountGmail,
            accountGmailPassword: this.editAccountForm.accountGmailPassword,
            accountChatgptPassword: this.editAccountForm.accountChatgptPassword,
            accountDetails: this.editAccountForm.accountDetails,
            accountBankNumber: this.editAccountForm.accountBankNumber,
            accountPaymentDate: "2025-01-10",
            accountOperatorId: this.accountOperatorId,
          },
        });
        this.editAccountForm.accountGmail = "";
        this.editAccountForm.accountGmailPassword = "";
        this.editAccountForm.accountChatgptPassword = "";
        this.editAccountForm.accountDetails = "";
        this.editAccountForm.accountBankNumber = "";
        this.$message.success("修改账户信息成功");
      } catch (error) {
        console.error("修改账户信息失败：", error);
        this.$message.error("无法修改账户信息");
      }
      this.dialogFormVisibleEditAccount = false;
      this.fetchAccountData(); // 重新获取账户数据
    },

    // 处理删除用户
    handleDeleteUser(userId) {
      this.open(userId);
    },
    open(userId) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 删除逻辑
          this.doDelete(userId);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async doDelete(userId) {
      try {
        await axios.get("http://8.155.162.119/api/user/deleteUser", {
          params: {
            userId: userId,
          },
        });
        this.$message.success("删除用户成功");
      } catch (error) {
        console.error("删除用户失败：", error);
        this.$message.error("无法删除用户");
      }
      this.fetchAccountData(); // 重新获取账户数据
    },

    // 处理申请账号
    async handleApplyForAccount() {
      try {
        const response = await axios.get(
          "http://8.155.162.119/api/account/addAccount",
          {
            params: {
              operatorId: this.user.id,
            },
          }
        );
        if (response.data.data.msg == "申请失败") {
          this.$message.error("您有的账号有空余位置，故不允许添加新的账号");
        } else {
          this.$message.success("申请账号成功");
        }
      } catch (error) {
        console.error("申请账号失败：", error);
        this.$message.error("无法申请账号");
      }
    },
  },

  async mounted() {
    // 页面加载时获取账户数据和用户数据
    await this.fetchAccountData();
  },
};
</script>
  
  <style scoped>
/* 分页样式 */
.block {
  margin-top: 5px;
  text-align: center;
}

.demonstration {
  display: block;
  margin-bottom: 10px;
  font-size: 14px;
  color: #909399;
}
</style>
  